<?php
namespace app\index\controller;

use think\Controller;
use app\index\model\PeopleModel;
use org\Verify;

class Login extends Controller
{
    /**
     * 登录
     * @return mixed
     */
    public function index()
    {
        if (request()->isPost()) {
            $phone = input("phone");
            $psw = input("psw");
            $code = input("code");

            $result = $this->validate(compact('phone', 'psw', "code"), 'LoginValidate');
            if(true !== $result){
                return json(['code' => -5, 'data' => '', 'msg' => $result]);
            }

            if(!$this->isMobile($phone)) {
                return json(['code' => 0, 'data' => '', 'msg' => '手机号码格式不正确']);
            }

            $verify = new Verify();
            if (!$verify->check($code)) {
                return json(['code' => -4, 'data' => '', 'msg' => '验证码错误']);
            }

            $hasPeople = db('people')->where('phone', $phone)->find();
            if(empty($hasPeople)){
                return json(['code' => -1, 'data' => '', 'msg' => '用户不存在']);
            }

            if(md5($psw) != $hasPeople['psw']){
                return json(['code' => -2, 'data' => '', 'msg' => '密码错误']);
            }

            session('phone', $phone);
            session('people_id', $hasPeople['id']);

            return json(['code' => 1, 'data' => '', 'msg' => '登录成功']);
        }

        return $this->fetch();
    }

    /**
     * 验证手机号是否正确
     * @param INT $mobile
     */
    private function isMobile($mobile) {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }
    /**
     * 注册
     * @return mixed
     */
    public function register()
    {
        if (request()->isPost()) {
            if(!$this->isMobile(input('phone'))) {
                return json(['code' => 0, 'data' => '', 'msg' => '手机号码格式不正确']);
            }
            $_POST['add_date'] = date('Y-m-d H:i:s');
            $_POST['psw'] = md5(input('psw'));
            $people = new PeopleModel();
            $flag = $people->insertPeople($_POST);

            if($flag['code'] == 1) {
                session('phone', input('phone'));
                session('people_id', $flag['data']);
            }
            return json(['code' => $flag['code'], 'data' => $flag['data'], 'msg' => $flag['msg']]);
        }
        return $this->fetch();
    }

    //验证码
    public function checkVerify()
    {
        $verify = new Verify();
//        $verify->imageH = 32;
//        $verify->imageW = 100;
        $verify->length = 4;
        $verify->useNoise = false;
        $verify->useCurve = false;
        $verify->fontSize = 14;
        return $verify->entry();
    }
}
